package com.justinbuser.singleton
{
	import com.justinbuser.net.DynamicURLLoader;
	
	import flash.desktop.NativeApplication;
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.utils.flash_proxy;

	use namespace flash_proxy;
	
	[Event(name="propertyChange", type="mx.events.PropertyChangeEvent")]
	[Event(name="statusChanged", type="flash.events.Event")]
	[Event(name="instanceChanged", type="flash.events.Event")]
	
	[Bindable("propertyChange")] 
	public dynamic class Core extends Controller
	{
		protected static var instance:*;
		
		public function Core(target:IEventDispatcher=null, classes:Vector.<Class>=null)
		{
			if(!instance)
			{
				super(target, classes);
				instance = this;
				dispatchEvent(new Event('instanceChanged'));
			}
		}

		[Bindable("instanceChanged")]
        public static function get core():Core
        {
			return instance ? instance : new Core();
        }
		
		[Bindable("statusChanged")]
        public static function get status():String
        {
            return core.status;
        }
		
        public static function set status(s:String):void
        {
			core.status = s;
			core.dispatchEvent(new Event('statusChanged'));
        }
		
		public static function clearSharedObject():void
		{
			core.clearSettings();
		}
		
		/*public static function saveSettings(properties:*):String
		{
			return core.saveProperties(properties);
		}
		
		protected function set status(s:String):void
        {
			FlexGlobals.topLevelApplication.status=s;
        }
		*/
		public static function networkError(e:IOErrorEvent):void{
			if(e.target is DynamicURLLoader){
				log.error("Error loading: "+e.target.uri+" on try number: "+e.target.loadsAttempted);
			}
		}
		
		public static function notifyUser(s:String,f:Function=null):void{
			log.info(s);
		}
		
		public static function hasSetting(s:String):Boolean{
			return core.hasProperty(s);
		}
		
		public static function shutdown(e:Event=null):void{
			log.debug('Shutting Down, saving settings response:',core.shutdown());
			NativeApplication.nativeApplication.exit();
		}
		
		public static function debugEvent(e:Event):void{ trace('Debug Event:',e.toString()); }
		public static function errorEvent(e:Event):void{ trace('Error Event:',e.toString()); }
		public static function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void{ dispatcher.addEventListener(type, listener, useCapture, priority); }
		public static function removeEventListener(type:String, listener:Function):void{ dispatcher.removeEventListener(type, listener); }
		public static function dispatchEvent(evt:Event):Boolean{ return dispatcher.dispatchEvent(evt); }
		
	}
}